<template>
  <div class="dialog">
    <el-dialog
      :title="'设备台账'+titleText"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-form
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item
          label="所属设备型号："
          prop="equModelCode"
          class="w50p"
        >
          <el-select
            v-model="formData.equModelCode"
            filterable
            clearable
          >
            <el-option
              v-for="item in equModelArr"
              :key="item.equModelCode"
              :label="item.modelName"
              :value="item.equModelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="设备名称："
          prop="equipmentName"
          class="w50p"
        >
          <el-input
            v-model="formData.equipmentName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item
          label="农机码："
          prop="imei"
          class="w50p"
        >
          <el-input
            v-model="formData.imei"
            placeholder="请输入农机码"
          />
        </el-form-item>
        <el-form-item
          label="是否展示工况数据："
          prop="operationMode"
          class="w50p"
        >
          <el-select
            v-model="formData.operationMode"
            filterable
            clearable
          >
            <el-option
              v-for="item in yesOrNoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="是否可自动驾驶："
          prop="selfDriving"
          class="w50p"
        >
          <el-select
            v-model="formData.selfDriving"
            filterable
            clearable
          >
            <el-option
              v-for="item in yesOrNoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="出厂序号："
          prop="serialNumber"
          class="w50p"
        >
          <el-input
            v-model="formData.serialNumber"
            placeholder="请输入设备名称"
          />
        </el-form-item>

        <el-form-item
          label="生产日期："
          prop="produceDate"
          class="w50p"
        >
          <el-date-picker
            v-model="formData.produceDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item
          label="品牌："
          prop="brand"
          class="w50p"
        >
          <el-input
            v-model="formData.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>
        <el-form-item
          label="生产企业："
          prop="manufacturer"
          class="w50p"
        >
          <el-input
            v-model="formData.manufacturer"
            placeholder="请输入生产企业"
          />
        </el-form-item>
        <el-form-item
          label="备注："
          prop="remark"
          class="w50p"
        >
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-divider content-position="left">购置信息</el-divider>
        <el-form-item
          label="购置日期："
          prop="purchaseDate"
          class="w50p"
        >
          <el-date-picker
            v-model="formData.purchaseDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择购置日期"
          />
        </el-form-item>

        <el-form-item
          label="质保期："
          prop="sellByDate"
          class="w50p"
        >
          <el-input
            v-model.number="formData.sellByDate"
            placeholder="请输入质保期"
          >
            <template slot="append">月</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="质保日期："
          prop="warrantyDate"
          class="w50p"
        >
          <el-date-picker
            v-model="formData.warrantyDate"
            type="date"
            value-format="yyyy-MM-dd"
            disabled
            placeholder="请选择生产日期和输入质保期"
          />
        </el-form-item>
        <el-form-item
          label="供应商："
          prop="taxpayerNumber"
          class="w50p"
        >
          <el-input
            v-model="formData.taxpayerNumber"
            placeholder="请输入供应商"
          />
        </el-form-item>
        <el-form-item
          label="补贴金额："
          prop="purchaseSubsidy"
          class="w50p"
        >
          <el-input
            v-model.trim="formData.purchaseSubsidy"
            type="number"
            clearable
            @input="($event) => {
            if($event.startsWith('0') && !$event.includes('.') && $event != 0){
              $set(formData, 'purchaseSubsidy', $event.replace(/\b(0+)/gi,''))
            }else{
              $set(formData, 'purchaseSubsidy', Math.abs($event))
            }}"
            placeholder="请输入补贴金额"
          />
        </el-form-item>
        <el-form-item
          label="购置金额："
          prop="purchaseAmount"
          class="w50p"
        >
          <el-input
            v-model="formData.purchaseAmount"
            clearable
            @input="($event) => {
            if($event.startsWith('0') && !$event.includes('.') && $event != 0){
              $set(formData, 'purchaseAmount', $event.replace(/\b(0+)/gi,''))
            }else{
              $set(formData, 'purchaseAmount', Math.abs($event))
            }}"
            placeholder="请输入购置金额"
          />
        </el-form-item>

        <el-form-item
          label="购置备注："
          prop="purchaseRemark"
          class="w50p"
        >
          <el-input
            v-model="formData.purchaseRemark"
            placeholder="请输入购置备注"
          />
        </el-form-item>

        <el-divider content-position="left">点位信息</el-divider>
        <el-form-item
          label="经度："
          prop="longitude"
          class="w50p"
        >
          <el-input
            v-model="formData.longitude"
            @input="(e) => { if (this.formData.latitude&&e) {this.lnglat =  [e, this.formData.latitude]} }"
            placeholder="请输入经度或者从下方地图选择"
          />
        </el-form-item>
        <el-form-item
          label="纬度："
          prop="latitude"
          class="w50p"
        >
          <el-input
            v-model="formData.latitude"
            @input="(e) => {if (this.formData.longitude&&e) { this.lnglat =  [this.formData.longitude, e]} }"
            placeholder="请输入纬度或者从下方地图选择"
          />
        </el-form-item>
        <div
          class="w100p"
          style="height: 49.5vh;"
        >
          <MapArea
            @getLngLat="getLngLat"
            :lnglat="lnglat"
          />
        </div>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          class="cancelbtn"
          @click="cancel()"
        >取 消</el-button>
        <el-button
          type="primary"
          class="savebtn"
          @click="save('ruleForm')"
        >保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 组件
import MapArea from "@/components/Amap/mapArea";
// Api 接口
import equipStandingBookApi from "@/api/equip-manage/equip-standing-book";

export default {
  name: "",
  components: { MapArea },
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      }
    },
    equModelArr: {
      type: [Array],
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      lnglat: [],
      // 展示
      formData: {},
      rules: {
        equModelCode: [
          {
            required: true,
            message: "请选择设备型号",
            trigger: ["blur", "change"]
          }
        ],
        equipmentName: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: ["blur", "change"]
          }
        ],
        operationMode: [
          {
            required: true,
            message: "请选择是否展示工况数据",
            trigger: ["blur", "change"]
          }
        ],
        produceDate: [
          {
            required: true,
            message: "请选择生产日期",
            trigger: ["blur", "change"]
          }
        ],
        purchaseDate: [
          {
            required: true,
            message: "请选择购置日期",
            trigger: ["blur", "change"]
          }
        ],
        sellByDate: [
          {
            required: true,
            message: "请输入质保期",
            trigger: ["blur", "change"]
          }
        ],
        selfDriving: [
          {
            required: true,
            message: "请选择是否可自动驾驶",
            trigger: ["blur", "change"]
          }
        ]
      },
      yesOrNoList: [
        { name: "是", id: true },
        { name: "否", id: false }
      ],
      showDialog: this.show,
      statusArr: [
        {
          name: "启用",
          id: "ENABLE"
        },
        {
          name: "废弃",
          id: "DISCARD"
        },
        {
          name: "维修中",
          id: "REPAIRING"
        },
        {
          name: "禁用",
          id: "DISABLE"
        }
      ]
    };
  },

  watch: {
    show(v) {
      this.showDialog = v;
      console.log("add dialog show");
    },
    nowChanceStau(v) {
      if (v === "add") {
        this.formData = {
          equipmentTypeCode: this.editObject.equipmentTypeCode
        };

      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      } else if (v === "edit") {
        this.formData = this.editObject;
      }
      console.log("nowChanceStau watch ", this.formData);
    },
    "formData.purchaseDate": {
      deep: true,
      handler(v) {
        if (v && this.formData.sellByDate) {
          var dt = new Date(v);
          dt.setMonth(dt.getMonth() + this.formData.sellByDate);
          //  document.write( dt );
          this.$set(this.formData, "warrantyDate", this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, "warrantyDate", "");
        }
      }
    },
    "formData.sellByDate": {
      deep: true,
      handler(v) {
        if (v && this.formData.purchaseDate) {
          var dt = new Date(this.formData.purchaseDate);
          dt.setMonth(dt.getMonth() + v);
          //  document.write( dt );
          this.$set(this.formData, "warrantyDate", this.dateToFormatTwo(dt));
        } else {
          this.$set(this.formData, "warrantyDate", "");
        }
      }
    }
  },
  computed: {
    // lnglat() {
    //   if (this.formData.longitude && this.formData.latitude) {
    //     return [this.formData.longitude, this.formData.latitude]
    //   }
    // }
  },
  created() {},
  mounted() {},
  methods: {
    getLngLat([longitude, latitude]) {
      this.$set(this.formData, "longitude", longitude);
      this.$set(this.formData, "latitude", latitude);
      this.lnglat = [longitude, latitude];
    },
    save(formData) {
      this.$refs[formData].validate(async valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            var index = this.statusArr.findIndex(
              a => a.name === this.formData.status
            );
            if (index !== -1) {
              this.formData.status = this.statusArr[index].id;
            }
            // const { data: res } = await equipStandingBookApi.queryBeOccupied(this.formData.equipmentName);
            // if (res === false) {
            equipStandingBookApi
              .edit({
                ...this.formData,
                organizationNo: sessionStorage.organizationNo
              })
              .then(res => {
                if (res.code === 1) {
                  this.$message.success("修改成功！");
                  this.close();
                }
              });
            // } else {
            //   this.$message.error("该设备名称已存在，请重新输入！")
            // }
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            const { data: res } = await equipStandingBookApi.queryBeOccupied(
              this.formData.equipmentName
            );
            if (res === false) {
              equipStandingBookApi
                .add({
                  ...this.formData,
                  organizationNo: sessionStorage.organizationNo
                })
                .then(res => {
                  if (res.code === 1) {
                    this.$message.success(res.msg);
                    this.close();
                  }
                });
            } else {
              this.$message.error("该设备名称已存在，请重新输入！");
            }
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.lnglat = [];

      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit("closeDialog");
    },
    cancel() {
      this.lnglat = [];

      this.$nextTick(() => {
        this.$refs['ruleForm']?.clearValidate();
      });
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 160px !important;
}
::v-deep {
  .el-divider__text {
    background-color: #f0f3f7;
  }
}
</style>
